<template>
  <div class="after-sales-management">
    <!-- 筛选栏 -->
    <el-form :inline="true" :model="filters" class="filter-form">
      <el-form-item label="订单号">
        <el-input
          v-model="filters.orderId"
          placeholder="请输入订单号"
          clearable
        />
      </el-form-item>
      <el-form-item label="商品状态">
        <el-select v-model="filters.productStatus" placeholder="全部" clearable>
          <el-option label="全部" value="" />
          <el-option label="退款中" value="退款中" />
          <el-option label="已退款" value="已退款" />
          <el-option label="退款失败" value="退款失败" />
        </el-select>
      </el-form-item>
      <el-form-item label="申请时间">
        <el-date-picker
          v-model="filters.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSearch">搜索</el-button>
        <el-button @click="onReset">重置</el-button>
      </el-form-item>
    </el-form>

    <!-- 统计数据 -->
    <div class="stat-bar">
      <el-tag type="warning">退款中: {{ stat.refunding }}</el-tag>
      <el-tag type="success">已退款: {{ stat.refunded }}</el-tag>
      <el-tag type="danger">退款失败: {{ stat.refundFailed }}</el-tag>
    </div>

    <!-- 表格 -->
    <el-table
      :data="pagedData"
      border
      style="width: 100%"
      v-loading="loading"
      @selection-change="onSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="orderId" label="订单号" width="150" />
      <el-table-column prop="refundTime" label="申请退款时间" width="180">
        <template #default="{ row }">
          {{ formatDate(row.refundTime) }}
        </template>
      </el-table-column>
      <el-table-column prop="refundAmount" label="退款金额" width="120">
        <template #default="{ row }">
          <span class="amount">¥{{ row.refundAmount }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="productStatus" label="商品状态" width="120">
        <template #default="{ row }">
          <el-tag :type="getProductStatusType(row.productStatus)">
            {{ row.productStatus }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="refundReason" label="退款原因" width="200" show-overflow-tooltip />
      <el-table-column prop="auditStatus" label="审核状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getAuditStatusType(getAuditStatus(row.productStatus))">
            {{ getAuditStatus(row.productStatus) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column prop="auditor" label="审核人" width="100">
        <template #default="{ row }">
          {{ row.auditor || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button 
            type="primary" 
            size="small" 
            @click="onView(row)"
          >
            查看
          </el-button>
          <el-button 
            v-if="row.productStatus === '退款中'"
            type="success" 
            size="small" 
            @click="onApprove(row)"
          >
            通过
          </el-button>
          <el-button 
            v-if="row.productStatus === '退款中'"
            type="danger" 
            size="small" 
            @click="onReject(row)"
          >
            驳回
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-wrapper">
      <el-pagination
        background
        layout="total, sizes, prev, pager, next, jumper"
        :total="filteredData.length"
        :page-size="pageSize"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100]"
        @current-change="onPageChange"
        @size-change="onSizeChange"
      />
    </div>

    <!-- 查看详情弹窗 -->
    <el-dialog
      v-model="viewDialogVisible"
      title="退款详情"
      width="600px"
    >
      <div v-if="currentRecord">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单号">{{ currentRecord.orderId }}</el-descriptions-item>
          <el-descriptions-item label="申请退款时间">{{ formatDate(currentRecord.refundTime) }}</el-descriptions-item>
          <el-descriptions-item label="退款金额">¥{{ currentRecord.refundAmount }}</el-descriptions-item>
          <el-descriptions-item label="商品状态">
            <el-tag :type="getProductStatusType(currentRecord.productStatus)">
              {{ currentRecord.productStatus }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="退款原因" :span="2">{{ currentRecord.refundReason }}</el-descriptions-item>
          <el-descriptions-item label="审核状态">
            <el-tag :type="getAuditStatusType(getAuditStatus(currentRecord.productStatus))">
              {{ getAuditStatus(currentRecord.productStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="申请用户">{{ currentRecord.userName }}</el-descriptions-item>
          
          <!-- 已审核的订单显示审核信息 -->
          <template v-if="currentRecord.productStatus === '已退款' || currentRecord.productStatus === '退款失败'">
            <el-descriptions-item label="审核时间" v-if="currentRecord.auditTime">
              {{ formatDate(currentRecord.auditTime) }}
            </el-descriptions-item>
            <el-descriptions-item label="审核人" v-if="currentRecord.auditor">
              {{ currentRecord.auditor }}
            </el-descriptions-item>
            <el-descriptions-item label="审核备注" :span="2" v-if="currentRecord.auditRemark">
              {{ currentRecord.auditRemark }}
            </el-descriptions-item>
          </template>
          
          <!-- 待审核的订单显示提示 -->
          <template v-else>
            <el-descriptions-item label="审核时间">-</el-descriptions-item>
            <el-descriptions-item label="审核人">-</el-descriptions-item>
            <el-descriptions-item label="审核备注" :span="2">-</el-descriptions-item>
          </template>
        </el-descriptions>
        
        <!-- 退款凭证图片 -->
        <div v-if="currentRecord.evidencePhotos && currentRecord.evidencePhotos.length > 0" style="margin-top: 20px;">
          <h4 style="margin-bottom: 15px; color: #333;">退款凭证</h4>
          <div style="display: flex; flex-wrap: wrap; gap: 10px;">
            <div 
              v-for="(photo, index) in currentRecord.evidencePhotos" 
              :key="index"
              style="position: relative; cursor: pointer;"
              @click="previewImage(photo)"
            >
              <img 
                :src="photo" 
                :alt="`退款凭证${index + 1}`"
                style="width: 100px; height: 100px; object-fit: cover; border-radius: 4px; border: 1px solid #ddd;"
              />
            </div>
          </div>
        </div>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关闭</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 审核弹窗 -->
    <el-dialog
      v-model="auditDialogVisible"
      :title="auditType === 'approve' ? '通过退款申请' : '驳回退款申请'"
      width="500px"
    >
      <div v-if="currentRecord">
        <el-form :model="auditForm" label-width="100px">
          <el-form-item label="订单号">
            <span>{{ currentRecord.orderId }}</span>
          </el-form-item>
          <el-form-item label="退款金额">
            <span>¥{{ currentRecord.refundAmount }}</span>
          </el-form-item>
          <el-form-item label="退款原因">
            <span>{{ currentRecord.refundReason }}</span>
          </el-form-item>
          <el-form-item label="审核备注">
            <el-input
              v-model="auditForm.remark"
              type="textarea"
              :rows="3"
              :placeholder="auditType === 'approve' ? '请输入通过备注（可选）' : '请输入驳回原因'"
            />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="auditDialogVisible = false">取消</el-button>
          <el-button 
            :type="auditType === 'approve' ? 'success' : 'danger'"
            @click="confirmAudit"
            :loading="loading"
          >
            {{ auditType === 'approve' ? '确认通过' : '确认驳回' }}
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import axios from "axios";

// 响应式数据
const loading = ref(false);
const currentPage = ref(1);
const pageSize = ref(10);
const viewDialogVisible = ref(false);
const auditDialogVisible = ref(false);
const currentRecord = ref(null);
const auditType = ref('');
const selectedRecords = ref([]);
const afterSalesList = ref([]);

// 筛选条件
const filters = reactive({
  orderId: "",
  productStatus: "",
  dateRange: []
});

// 审核表单
const auditForm = reactive({
  remark: ""
});

// 统计数据
const stat = reactive({
  refunding: 0,
  refunded: 0,
  refundFailed: 0
});

// 获取售后列表数据
const fetchAfterSalesList = async () => {
  try {
    loading.value = true;
    const response = await axios.get('http://localhost:3000/hy/after-sales');
    
    if (response.data.code === 200) {
      afterSalesList.value = response.data.data || [];
      updateStats();
    } else {
      ElMessage.error(response.data.message || '获取售后列表失败');
    }
  } catch (error) {
    console.error('获取售后列表失败:', error);
    ElMessage.error('获取售后列表失败');
  } finally {
    loading.value = false;
  }
};

// 计算属性
const filteredData = computed(() => {
  let data = afterSalesList.value;
  
  // 订单号筛选
  if (filters.orderId) {
    data = data.filter(item => 
      item.orderId.toLowerCase().includes(filters.orderId.toLowerCase())
    );
  }
  
  // 商品状态筛选
  if (filters.productStatus) {
    data = data.filter(item => item.productStatus === filters.productStatus);
  }
  
  // 日期范围筛选
  if (filters.dateRange && filters.dateRange.length === 2) {
    const startDate = new Date(filters.dateRange[0]);
    const endDate = new Date(filters.dateRange[1]);
    data = data.filter(item => {
      const refundDate = new Date(item.refundTime);
      return refundDate >= startDate && refundDate <= endDate;
    });
  }
  
  return data;
});

const pagedData = computed(() => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return filteredData.value.slice(start, end);
});

// 更新统计数据
const updateStats = () => {
  stat.refunding = afterSalesList.value.filter(item => item.productStatus === '退款中').length;
  stat.refunded = afterSalesList.value.filter(item => item.productStatus === '已退款').length;
  stat.refundFailed = afterSalesList.value.filter(item => item.productStatus === '退款失败').length;
};

// 工具函数
const formatDate = (dateString) => {
  if (!dateString) return '-';
  return new Date(dateString).toLocaleString('zh-CN');
};

// 根据商品状态获取审核状态
const getAuditStatus = (productStatus) => {
  const statusMap = {
    '退款中': '待审核',
    '已退款': '已通过',
    '退款失败': '已驳回'
  };
  return statusMap[productStatus] || '未知';
};

const getAuditStatusType = (auditStatus) => {
  const statusMap = {
    '待审核': 'warning',
    '已通过': 'success',
    '已驳回': 'danger'
  };
  return statusMap[auditStatus] || 'info';
};

const getProductStatusType = (status) => {
  const statusMap = {
    '退款中': 'warning',
    '已退款': 'success',
    '退款失败': 'danger'
  };
  return statusMap[status] || 'info';
};

// 事件处理
const onSearch = () => {
  currentPage.value = 1;
};

const onReset = () => {
  Object.assign(filters, {
    orderId: "",
    productStatus: "",
    dateRange: []
  });
  currentPage.value = 1;
};

const onPageChange = (page) => {
  currentPage.value = page;
};

const onSizeChange = (size) => {
  pageSize.value = size;
  currentPage.value = 1;
};

const onSelectionChange = (selection) => {
  selectedRecords.value = selection;
};

// 查看详情
const onView = async (row) => {
  try {
    loading.value = true;
    
    // 调用后端详情接口获取最新数据
    const response = await axios.get(`http://localhost:3000/hy/after-sales/${row.id}`);
    
    if (response.data.code === 200) {
      currentRecord.value = response.data.data;
      viewDialogVisible.value = true;
    } else {
      ElMessage.error(response.data.message || '获取详情失败');
    }
  } catch (error) {
    console.error('获取详情失败:', error);
    ElMessage.error('获取详情失败，请重试');
  } finally {
    loading.value = false;
  }
};

// 通过审核
const onApprove = (row) => {
  currentRecord.value = row;
  auditType.value = 'approve';
  auditForm.remark = '';
  auditDialogVisible.value = true;
};

// 驳回审核
const onReject = (row) => {
  currentRecord.value = row;
  auditType.value = 'reject';
  auditForm.remark = '';
  auditDialogVisible.value = true;
};

// 获取当前用户信息
const getCurrentUser = () => {
  const token = localStorage.getItem('accessToken');
  if (!token) return null;
  
  try {
    const parts = token.split('.');
    if (parts.length !== 3) return null;
    
    // 处理base64url编码
    let base64 = parts[1].replace(/-/g, '+').replace(/_/g, '/');
    
    // 补齐padding
    const padLength = 4 - (base64.length % 4);
    if (padLength < 4) {
      base64 += '='.repeat(padLength);
    }
    
    // 解码base64并正确处理UTF-8字符
    const decoded = decodeURIComponent(
      atob(base64)
        .split('')
        .map(c => '%' + ('00' + c.charCodeAt(0).toString(16)).slice(-2))
        .join('')
    );
    
    return JSON.parse(decoded);
  } catch (error) {
    console.error('Token解析失败:', error);
    return null;
  }
};

// 确认审核
const confirmAudit = async () => {
  if (auditType.value === 'reject' && !auditForm.remark.trim()) {
    ElMessage.warning('请输入驳回原因');
    return;
  }
  
  try {
    loading.value = true;
    
    // 获取当前用户信息
    const currentUser = getCurrentUser();
    const auditor = currentUser?.realName || currentUser?.userName || '管理员';
    
    console.log('审核操作:', {
      action: auditType.value,
      recordId: currentRecord.value?.id,
      orderId: currentRecord.value?.orderId,
      auditor: auditor
    });
    
    // 优先使用id，如果没有则使用orderId
    const recordId = currentRecord.value?.id || currentRecord.value?.orderId;
    
    const response = await axios.put(`http://localhost:3000/hy/after-sales/${recordId}/status`, {
      action: auditType.value, // 'approve' 或 'reject'
      auditRemark: auditForm.remark,
      auditor: auditor
    });
    
    console.log('审核响应:', response.data);
    
    if (response.data.code === 200) {
      // 更新本地数据
      const record = afterSalesList.value.find(item => item.id === currentRecord.value.id);
      if (record) {
        record.productStatus = response.data.data.productStatus;
        record.auditRemark = response.data.data.auditRemark;
        record.auditTime = response.data.data.auditTime;
        record.auditor = response.data.data.auditor;
      }
      
      // 更新统计数据
      updateStats();
      
      auditDialogVisible.value = false;
      ElMessage.success(response.data.message);
      // 关闭弹窗
      auditDialogVisible.value = false;
    }
  } catch (error) {
    // 关闭弹窗
    auditDialogVisible.value = false; 
  } finally {
    loading.value = false;
  }
};

// 预览图片
const previewImage = (url) => {
  ElMessageBox.previewImage({
    images: [url],
    initialIndex: 0,
    zIndex: 999999,
  });
};

// 初始化
onMounted(() => {
  fetchAfterSalesList();
});
</script>

<style scoped>
.after-sales-management {
  padding: 20px;
}

.filter-form {
  background: #fff;
  padding: 20px;
  border-radius: 8px;
  margin-bottom: 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}

.stat-bar {
  margin-bottom: 20px;
}

.stat-bar .el-tag {
  margin-right: 15px;
  font-size: 14px;
}

.amount {
  color: #f56c6c;
  font-weight: bold;
}

.pagination-wrapper {
  margin-top: 20px;
  text-align: center;
}

.dialog-footer {
  text-align: right;
}
</style>